package com.goldcn.config;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by   on 2016/5/6.
 */

@ConfigurationProperties(prefix = "elastic")
public class ElasticsearchBean {
    private String clusterName;
    private String host;
    private Integer indexPort;
    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchBean.class);

    @Bean(name = "client")
    public Client getESClient() {
        try {
            return getTransportClient(clusterName, host, indexPort);
        } catch (Exception e) {
            logger.error("getClient", e);
        }
        return null;
    }

    private TransportClient getTransportClient(String cluster, String host, int port) throws UnknownHostException {
        try {

            //自动配置集群IP  put("cluster.name", "myClusterName")设置集群名。默认为elasticsearch
            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", clusterName)
                    .put("client.transport.sniff", false).build();
            TransportClient transportClient = TransportClient.builder().settings(settings).build().
                    addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
            return transportClient;
        } catch (Exception e) {
            logger.error("getTransportClient", e);
        }
        return null;
    }

    public String getClusterName() {
        return clusterName;
    }

    public void setClusterName(String clusterName) {
        this.clusterName = clusterName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getIndexPort() {
        return indexPort;
    }

    public void setIndexPort(Integer indexPort) {
        this.indexPort = indexPort;
    }
}
